// pages/preToDo/preToDo.js
import tool from '../../modules/tool'
import store from '../../modules/store'

Page({

  /**
   * 页面的初始数据
   */
  data: {
    list: [],
    size: 100000,
    count: 0,
    requesting: false,
    first: true,
    showMask: false
  },

  handleOpButtonClick(e) {
    e = e.currentTarget.dataset
    console.log(e)
    if (e.op == 'call') {
      wx.makePhoneCall({
        phoneNumber: e.item.phone,
      })
    }
    if (e.op == 'wait' || e.op == 'send' || e.op == 'ok') {
      tool.handleShowModel((() => {
        if (e.op == 'wait') return `请确认订单【${e.item.code}】已完成备餐，此操作会向用户发送通知，是否通知用户取餐？`
        if (e.op == 'send') return `请确认订单【${e.item.code}】已完成备餐，此操作会向用户发送通知，是否通知用户正在配送？`
        if (e.op == 'ok') return `请确认订单【${e.item.code}】已被用户收到，是否将此订单设为已完成状态？`
      })(), true, async () => {
        let re = await tool.requestData('/order/updateStatus', {
          orderNo: e.item.orderNo,
          status: (() => {
            if (e.op == 'send') return 2
            if (e.op == 'wait') return 3
            if (e.op == 'ok') return 4
          })()
        })
        if (re.status) {
          if (e.op == 'ok') {
            await tool.wait(0.2)
            tool.handleShowToast(`订单【${e.item.code}】已完成`, 'success', 2000)
          }
        } else {
          tool.handleShowToast(re.content, 'error')
        }
      })
    }
    if (e.op == 'more') {
      tool.showOrderStatusPage(e.item.orderNo)
    }
  },

  showUserInfo(e) {
    tool.handleShowUserInfoPage(e.currentTarget.dataset.openid)
  },

  handleScan(){
    tool.handleScan()
  },

  async updateStatus() {
    let ids = this.getExistIds()
    let re = await tool.requestData('/order/getStatusList', {
      orderNos: ids
    }, 'post', false)
    if (re.status) {
      let t = this.data.list
      for (let i = 0; i < t.length; i++) {
        let orderNo = t[i].orderNo
        let status = undefined
        for (let i1 = 0; i1 < re.data.length; i1++) {
          if (re.data[i1].orderNo == orderNo) {
            if (re.data[i1].status == 4) {
              break
            }
            status = re.data[i1].status
            break
          }
        }
        if (status !== undefined) {
          t[i].status = status
          t[i].statusInfo.status = status
        } else {
          t = [...t.slice(0, i), ...t.slice(i + 1)]
        }
      }
      this.setData({
        list: t
      })
      this.refreshData()
    } else {
      console.log(re.content)
    }
  },

  refreshData() {
    this.setData({
      list: (() => {
        let t = this.data.list
        for (let i = 0; i < t.length; i++) {
          if (t[i].status == 1) t[i].statusColor = 'rgb(0,120,215)'
          if (t[i].status == 2) t[i].statusColor = 'green'
          if (t[i].status == 3) t[i].statusColor = '#f7630c'
        }
        return t
      })()
    })
  },

  getExistIds() {
    let re = []
    for (let i = 0; i < this.data.list.length; i++) {
      re.push(this.data.list[i].orderNo)
    }
    return [...new Set(re)]
  },

  async getOrders(type) {
    this.setData({
      count: 0,
      requesting: true
    })
    let ids = this.getExistIds()
    let orderNo = ids.length ? (type ? (ids[0]) : (ids[ids.length - 1])) : ('')
    let re = await tool.requestData('/order/getPreToDoOrders', {
      orderNo,
      type: orderNo == '' ? 0 : type,
      size: this.data.size
    }, 'get', false)
    let lst = []
    if (re.status) {
      if (type) {
        lst = [...re.data.list, ...this.data.list].sort((a, b) => {
          return new Date(b.paidAt) - new Date(a.paidAt)
        })
      } else {
        if (orderNo) {
          lst = [...this.data.list, ...re.data.list].sort((a, b) => {
            return new Date(b.paidAt) - new Date(a.paidAt)
          })
        } else {
          lst = re.data.list.sort((a, b) => {
            return new Date(b.paidAt) - new Date(a.paidAt)
          })
        }
      }
    } else {
      console.log(re.content)
      return
    }

    if (this.data.first) {
      this.setData({
        first: false,
        list: lst
      })
      this.refreshData()
    } else {
      if (type == 1) {

        let c = 0

        for (let i = 0; i < lst.length; i++) {
          if (ids.indexOf(lst[i].orderNo) == -1) {
            c++
          }
        }

        if (c) {

          this.setData({
            list: (() => {
              let t = lst
              for (let i = 0; i < t.length; i++) {
                t[i].anm = false
                t[i].scale = ids.indexOf(t[i].orderNo) == -1 ? 0.9 : 1
                t[i].opacity = ids.indexOf(t[i].orderNo) == -1 ? 0 : 1
                t[i].zIndex = ids.indexOf(t[i].orderNo) == -1 ? 20 : 0
                t[i].show = `translateY(-${c}00%)`
              }
              return t
            })(),
            showMask: true
          })
          this.refreshData()
          await tool.wait(0.01)

          this.setData({
            list: (() => {
              let t = this.data.list
              for (let i = 0; i < t.length; i++) {
                t[i].anm = true
                t[i].show = `translateY(0%)`
              }
              return t
            })(),
            showMask: true
          })
          await tool.wait(0.3)

          this.setData({
            list: (() => {
              let t = this.data.list
              for (let i = 0; i < t.length; i++) {
                t[i].scale = ids.indexOf(t[i].orderNo) == -1 ? 1.1 : 1
                t[i].opacity = 1
                t[i].show = '999rpx'
              }
              return t
            })(),
            showMask: true
          })
          await tool.wait(0.3)

          this.setData({
            list: (() => {
              let t = this.data.list
              for (let i = 0; i < t.length; i++) {
                t[i].scale = ids.indexOf(t[i].orderNo) == -1 ? 1 : 1
              }
              return t
            })(),
            showMask: false
          })
          await tool.wait(0.3)

          this.setData({
            list: (() => {
              let t = this.data.list
              for (let i = 0; i < t.length; i++) {
                t[i].scale = ids.indexOf(t[i].orderNo) == -1 ? 1.1 : 1
              }
              return t
            })(),
            showMask: true
          })
          await tool.wait(0.3)

          this.setData({
            list: (() => {
              let t = this.data.list
              for (let i = 0; i < t.length; i++) {
                t[i].scale = ids.indexOf(t[i].orderNo) == -1 ? 1 : 1
              }
              return t
            })(),
            showMask: false
          })
          await tool.wait(0.3)

          this.setData({
            list: (() => {
              let t = this.data.list
              for (let i = 0; i < t.length; i++) {
                t[i].scale = ids.indexOf(t[i].orderNo) == -1 ? 1 : 1
                t[i].zIndex = 0
              }
              return t
            })(),
            showMask: false
          })
        }



      } else {
        this.setData({
          list: lst
        })
        this.refreshData()
      }
    }

    this.setData({
      requesting: false
    })
    if (this.data.count) {
      this.getOrders(1)
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.getOrders(0)
    tool.webSocket.onMessage('newOrder', () => {
      this.setData({
        count: this.data.count + 1
      })
      this.getOrders(1)
    })
    tool.webSocket.onMessage('updateStatus', () => {
      this.updateStatus()
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  async onPullDownRefresh() {
    await this.getOrders(1)
    wx.stopPullDownRefresh()
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
    this.getOrders(0)
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})